<template>
  <div class="app-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef" size="small">
        <el-form-item label="患者姓名">
          <el-input v-model="searchForm.patientName" placeholder="请输入患者姓名" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="主诊医生">
          <el-input v-model="searchForm.doctorName" placeholder="请输入医生姓名" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <el-form-item label="科室">
          <el-select v-model="searchForm.departmentId" placeholder="请选择科室" clearable>
            <el-option 
              v-for="item in departmentOptions" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="草稿" value="草稿" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已签名" value="已签名" />
          </el-select>
        </el-form-item>
        <el-form-item label="就诊日期">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button 
            type="success" 
            v-permission="'medical_record:create'"
            @click="handleCreate"
          >
            <el-icon><Plus /></el-icon>新增病历
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card shadow="never" class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        row-key="id"
        stripe
      >
        <el-table-column label="就诊ID" prop="visitId" min-width="120" />
        <el-table-column label="患者姓名" min-width="100">
          <template #default="scope">
            <el-button type="text" @click="viewPatient(scope.row.patientId)">
              {{ scope.row.patientName }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="就诊日期" min-width="120">
          <template #default="scope">
            <span>{{ formatDate(scope.row.visitDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="科室" prop="departmentName" min-width="120" />
        <el-table-column label="主诊医生" prop="doctorName" min-width="100" />
        <el-table-column label="主诉" prop="chiefComplaint" min-width="180" show-overflow-tooltip />
        <el-table-column label="诊断" min-width="180" show-overflow-tooltip>
          <template #default="scope">
            <div v-if="scope.row.diagnosis && scope.row.diagnosis.length > 0">
              <div v-for="(diag, index) in scope.row.diagnosis" :key="index">
                {{ diag.name }}{{ index < scope.row.diagnosis.length - 1 ? '、' : '' }}
              </div>
            </div>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small"
              @click="handleView(scope.row)"
              v-permission="'medical_record:read'"
            >
              详情
            </el-button>
            <el-button 
              v-if="scope.row.status !== '已签名'"
              type="warning" 
              size="small"
              @click="handleEdit(scope.row)"
              v-permission="'medical_record:update'"
            >
              编辑
            </el-button>
            <el-dropdown>
              <el-button size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleViewRelated(scope.row)">
                    <el-icon><Connection /></el-icon>查看关联数据
                  </el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.status === '已完成'" @click="handleSignRecord(scope.row)">
                    <el-icon><Check /></el-icon>签名
                  </el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.status === '已完成'" @click="handleCreatePrescription(scope.row)">
                    <el-icon><Document /></el-icon>开处方
                  </el-dropdown-item>
                  <el-dropdown-item v-if="scope.row.status === '已完成'" @click="handleCreateMedicalOrder(scope.row)">
                    <el-icon><List /></el-icon>下医嘱
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { medicalRecordAPI, departmentAPI } from '@/utils/api'
import { formatDate } from '@/utils/date'

// 路由实例
const router = useRouter()

// 数据加载状态
const loading = ref(false)

// 表格数据
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 科室选项
const departmentOptions = ref([])

// 日期范围
const dateRange = ref([])

// 搜索表单
const searchFormRef = ref(null)
const searchForm = reactive({
  patientName: '',
  doctorName: '',
  departmentId: '',
  status: '',
  startDate: '',
  endDate: ''
})

// 处理日期范围变化
const handleDateRangeChange = (val) => {
  if (val) {
    searchForm.startDate = val[0]
    searchForm.endDate = val[1]
  } else {
    searchForm.startDate = ''
    searchForm.endDate = ''
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case '草稿':
      return ''
    case '已完成':
      return 'success'
    case '已签名':
      return 'primary'
    default:
      return 'info'
  }
}

// 获取医疗记录列表
const getMedicalRecords = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      ...searchForm
    }
    
    // 移除空字段
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const res = await medicalRecordAPI.getMedicalRecords(params)
    tableData.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    console.error('获取医疗记录列表失败', error)
    ElMessage.error('获取医疗记录列表失败')
  } finally {
    loading.value = false
  }
}

// 获取科室列表
const getDepartments = async () => {
  try {
    const res = await departmentAPI.getDepartments({ status: '启用' })
    departmentOptions.value = res.data.departments
  } catch (error) {
    console.error('获取科室列表失败', error)
  }
}

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1
  getMedicalRecords()
}

// 重置搜索条件
const resetSearch = () => {
  searchFormRef.value.resetFields()
  dateRange.value = []
  searchForm.startDate = ''
  searchForm.endDate = ''
  currentPage.value = 1
  getMedicalRecords()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getMedicalRecords()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getMedicalRecords()
}

// 新增病历
const handleCreate = () => {
  router.push('/medical-records/create')
}

// 查看病历
const handleView = (row) => {
  // 检查是否在门户医生页面，如果是则使用门户路由
  const currentPath = router.currentRoute.value.path
  if (currentPath.includes('/portal/doctor')) {
    router.push(`/portal/doctor/medical-record/${row.id}`)
  } else {
    router.push(`/medical-records/detail/${row.id}`)
  }
}

// 编辑病历
const handleEdit = (row) => {
  router.push(`/medical-records/edit/${row.id}`)
}

// 查看关联数据（处方和医嘱）
const handleViewRelated = (row) => {
  // 导航到医疗记录详情页面，专门显示关联数据
  const currentPath = router.currentRoute.value.path
  if (currentPath.includes('/portal/doctor')) {
    router.push(`/portal/doctor/medical-record/${row.id}`)
  } else {
    router.push(`/medical-records/detail/${row.id}`)
  }
}

// 查看患者
const viewPatient = (patientId) => {
  router.push(`/patients/detail/${patientId}`)
}

// 签名病历
const handleSignRecord = async (row) => {
  try {
    await medicalRecordAPI.updateMedicalRecord(row.id, { status: '已签名' })
    ElMessage.success('病历签名成功')
    getMedicalRecords()
  } catch (error) {
    console.error('病历签名失败', error)
    ElMessage.error(error.message || '病历签名失败')
  }
}

// 开处方
const handleCreatePrescription = (row) => {
  router.push({
    path: '/prescriptions/create',
    query: {
      patientId: row.patientId,
      medicalRecordId: row.id,
      doctorId: row.doctorId,
      departmentId: row.departmentId
    }
  })
}

// 下医嘱
const handleCreateMedicalOrder = (row) => {
  router.push({
    path: '/medical-orders/create',
    query: {
      patientId: row.patientId,
      medicalRecordId: row.id,
      doctorId: row.doctorId,
      departmentId: row.departmentId
    }
  })
}

// 页面加载时获取数据
onMounted(() => {
  getDepartments()
  getMedicalRecords()
})
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 